Write a MongoDB query to update specific fields in multiple documents in a collection.
Write a MongoDB query to update specific fields in multiple documents in a collection.
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
27-Jul-2023Sure, here is a MongoDB query to update specific fields in multiple documents in a collection:
This query updates the
age
andaddress
fields in all documents in the collection where thename
field is equal toJohn Doe
. The$set
operator is used to update the fields, and the values of the fields are specified in the object literal.For example, if the collection contains the following documents:
Then, the query would update the
age
andaddress
fields in the first document to 35 and123 Main Street
, respectively. The second document would not be updated, because thename
field does not match the filter.To run this query, you would need to connect to the MongoDB database and get the collection. Then, you could execute the query using the
updateMany()
method.Here is an example of how you could run the query:
This code would connect to the MongoDB database and get the
people
collection. Then, it would execute the query to update theage
andaddress
fields in the document where thename
field is equal toJohn Doe
.